package GoogleSpellChecker;

import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;


import util.HttpClientUtil;
import GoogleSpellChecker.jaxb.SpellRequest;
import GoogleSpellChecker.jaxb.SpellResult;

public class SpellChecker {

	public static void main(String[] args){
		String textToCheck = "ths is florst!";
		String url = "https://www.google.com/tbproxy/spell?lang=en&hl=en";
		
		try {
			String xmlForCheck = generateXMLForSpellChecker(textToCheck);
			HttpEntity entity = new ByteArrayEntity(xmlForCheck.getBytes());
			InputStream retIS = HttpClientUtil.doPost(url, entity);
			
	        JAXBContext jc = JAXBContext.newInstance(SpellResult.class);
	        Unmarshaller um = jc.createUnmarshaller();
	        SpellResult sr = (SpellResult) um.unmarshal(retIS);
	        
	        for(int i=0;i<sr.getC().size();i++){
	        	System.out.println(sr.getC().get(i).getVal() + " " + sr.getC().get(i).getLength());
	        }
        	System.out.println(sr.getCharschecked());
        	System.out.println(sr.getClipped());
        	System.out.println(sr.getError());

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	public static String generateXMLForSpellChecker(String textToCheck) throws JAXBException{
		SpellRequest sr = new SpellRequest();
		sr.setText(textToCheck);
		sr.setTextalreadyclipped("0");
		sr.setIgnoredups("0");
		sr.setIgnoredigits("0");
		sr.setIgnoreallcaps("0");
		
        JAXBContext jc = JAXBContext.newInstance(SpellRequest.class);

        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        StringWriter writer = new StringWriter();
        m.marshal(sr, writer);
        return writer.toString();
	}
	
	
}
